import { EN_NUMBER } from './utils/regulars.js'

let oDiv = document.getElementById('content')
let selRanges = [0, 0]
oDiv.focus()
setCursorPosition(0)

oDiv.addEventListener('beforeinput', e => {
  e.preventDefault()
  // console.log(e)
  let inputType = e.inputType
  let inputValue = e.data
  switch (inputType) {
    case 'insertText':
      if (EN_NUMBER.test(inputValue)) {
        oDiv.innerHTML += inputValue
        setCursorPosition(1)
      }
      break;
    case 'deleteContentBackward':
      let ov = oDiv.innerHTML
      if (selRanges[0] === selRanges[1]) {
        oDiv.innerHTML = ov.slice(0, -1)
      } else {
        console.log(ov.slice(0, selRanges[0]), ov.slice(selRanges[1], ov.length))
        oDiv.innerHTML = ov.slice(0, selRanges[0]) + ov.slice(selRanges[1], ov.length)
        // setCursorPosition(selRanges[1])
      }
      let len = oDiv.innerHTML.length
      setCursorPosition(len ? 1 : 0)
  }
})

oDiv.addEventListener('click', e => {
  getCursorPosition()
})

function getCursorPosition() {
  let sel = window.getSelection()
  console.log(sel)
  selRanges = [sel.focusOffset, sel.anchorOffset].sort()
}

function setCursorPosition(offset) {
  let sel = window.getSelection()
  let range = document.createRange()
  range.setStart(oDiv, offset)
  range.setEnd(oDiv, offset)
  sel.removeAllRanges()
  sel.addRange(range)
}